package org.xu.upms.server.common;

import java.util.Date;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;



public class LocalTokenManager extends TokenManager{
	
	
	private final ConcurrentHashMap<String, DummyUser>  dummyMap = new ConcurrentHashMap<String, DummyUser>();
	/**
	 * token过期 清除
	 */
	@Override
	public void verifyExpired() {
		Date now = new Date();
		for (Entry<String, DummyUser> entry : dummyMap.entrySet()) {
			String token = entry.getKey();
			DummyUser dummyUser = entry.getValue(); 
			//当前时间大于过期时间就清除
			if(now.compareTo(dummyUser.expired) > 0){
				dummyMap.remove(token);
			}
		}
	}

	@Override
	public void addToken(String token,LoginUser loginUser) {
		DummyUser dummyUser = new DummyUser();
		dummyUser.loginUser=loginUser;
		//设置过期时间
		extendExpiredtime(dummyUser);
		//如果指定键已经不再与某个值相关联，则将它与给定值关联 ,只有在map不包含这个键时，才能将键加入到map中。如果map已经包含这个键，那么这个键的现有值就会保留
		dummyMap.putIfAbsent(token, dummyUser);
	}

	@Override
	public void removeToken(String token) {
		dummyMap.remove(token);
	}

	@Override
	public LoginUser validate(String token) {
			DummyUser dummyUser =dummyMap.get(token);
			if(dummyUser==null){
				return null;
			}
			extendExpiredtime(dummyUser);
		return dummyUser.loginUser;
	}
	//扩展过期时间
	private DummyUser extendExpiredtime(DummyUser dummyUser){
		dummyUser.expired = new Date(new Date().getTime()+this.tokenTimeout*1000);
		return dummyUser;
	}
	
	private class DummyUser {
		private LoginUser loginUser;
		private Date expired; // 过期时间
	}
}
